<template>
  <yt-page title="视频列表" scroll>
    <yt-cell-cascader desc="所属组织机构" class="fixed-top" v-model="select" :list="tree" label="label" val="label" changeOnSelect showLast></yt-cell-cascader>
    <div class="video-box">
      <div v-for="(video, index) in videos" :key="index" @click="onClickVideo(video)" class="video-item">
        <img :src="require('./img/zanting.png')">
        <span>{{video.DeviceName}}</span>
      </div>
    </div>
  </yt-page>
</template>

<script>
import Mmbs from 'mmbs'
import { JudgeRole, Store, GetStore } from '@/store'
import { commonApi } from '@/common/api/commonApi.js'
import { BuildTree, findNodeFromTree, findChildrenFromTree } from '@/common/utils'
import { bridge } from '@/common/plugin/utils/bridge'
import { orgGridTree } from './orgGridTree'

// 默认徐圩新区安监流媒体地址
const streamObjDefault = {
  name: '流媒体地址',
  protocol: 'http',
  ip: '218.92.104.98',
  port: '8388',
  beforeDes: '/mag/hls/',
  filedNameFromVideos: 'DeviceNum',
  afterDes: '/0/live.m3u8'
}
/**
 * 常见流媒体地址
 * RTMP rtmp://live.hkstv.hk.lxdns.com/live/hks(香港卫视)
 * RTSP rtsp://184.72.239.149/vod/mp4://BigBuckBunny_175k.mov（大熊图点播）
 * HTTP http://ivi.bupt.edu.cn/hls/cctv1hd.m3u8（CCTV 1高清）
 */
const IsStreamAddress = (url) => {
  let protocol = url.split(':')[0]
  if (protocol === 'rtmp' || protocol === 'rtsp') {
    return true
  } else if (protocol === 'http' || protocol === 'https') {
    let afterWord = url.substr(url.lastIndexOf('.'))
    if (afterWord === '.m3u8' || afterWord === '.flv') return true
  }
  return false
}

export default {
  data() {
    return {
      tree: [],
      list: [],
      select: [],
      streamObj: null,
      videos: []
    }
  },
  watch: {
    select(ids) {
      if (ids.length) {
        let nodes = findNodeFromTree(this.tree, [ids[ids.length - 1]], 'label')
        this.onRefresh(nodes[0])
      }
    }
  },
  async activated() {
    if (!this.$router.$isBack) {
      if (!this.streamObj) this.streamObj = await this.fetchStreamAddress()
      this.select = []
      this.fetchGridTree()
    }
  },
  methods: {
    async fetchGridTree() {
      let tree = await orgGridTree.buildTree()
       await JudgeRole()
        .enterprise(async () => {
          let id = GetStore(Store.organization).id
          this.tree = await orgGridTree.buildTree('enterprise', id)
          this.select = [this.tree[0].label]
        })
        .fail(() => {
          this.tree = tree
          this.select = [this.tree[0].label]
        })
    },
    async fetchStreamAddress() {
      try {
        let resault = await commonApi.search('sys_setting')
        return resault.find(v => v.name === '流媒体地址') || null
      } catch (e) {
        // 请配置流媒体地址
      }
      return null

    },
    async onRefresh(node) {
      this.videos = []
        if (node.children) {
          if (node.children.length > 0) {
            node.children.forEach(v => {
              if (v.value && v.value.length > 0) {
                v.value.forEach(v2 => {
                  this.videos.push(v2)
                })
              }
            })
          }
        } else {
          this.videos = node.value
        }
    },
    async onClickVideo(video) {
      if (video.videoType && video.videoType === 'video_type_8700') {
        video.AddressIP = video.DeviceName
      }

      if (video.videoType && video.videoType === 'video_type_8200') {
        // TODO 待测试
        video.AddressIP = await commonApi.runCloud('getSecretKeys', {indexCode: video.AddressIP})
      }

      let isStream = IsStreamAddress(video.AddressIP)
      if (isStream) {
        bridge.Play(video.AddressIP)
      } else {
        this.$router.$push({
          path: '/base/play',
          query: { name: video.DeviceName, url: video.AddressIP }
        })
      }
    }
  }
}
</script>

<style scoped lang="stylus">
>>>.yt-cellCascader
  position relative
  z-index 1
>>>.yt-pull-scroll
  display inline-block
  padding-bottom 50px
>>>.video-item
  width 50%
  float left
  text-align center
  padding 10px
  box-sizing border-box
  line-height 30px
  .video-img
    padding-top 78%
    background-color rgba(0, 0, 0, 0.2)
  img
    max-width 100%
</style>
